package com.kuizii.server.net;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author renxiaodong
 */
public class HealthBeatServerHandler extends ChannelHandlerAdapter {

    private int lossConnectCount = 0;

    List<String> clientIps = new ArrayList<>();

    public void init(List<String> clients) {
        clientIps = clients;
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("已经15秒未收到客户端的消息了！"+ LocalDateTime.now());
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                lossConnectCount++;
                if (lossConnectCount > 2) {
                    System.out.println("关闭这个不活跃通道！");
                    System.out.println(ctx.channel().remoteAddress());
                    ctx.channel().close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
            lossConnectCount = 0;
        }
    }

}
